var Play = (function(){
	var catItemFun,
		songListFun;
	var songMedia,
		curSong;
	var contentType = ['playlist', 'cover', 'lyric', 'text', 'translation'],
	    curContentIndex = 1;

	//pl short for playinglist
	var plTplFun,
		playingCat,
		playingMode;
	var modeList = ['loop','random', 'order', 'single'];
	function update(){
		var voaData = VoaStorage.getStorage();
		var html = '';
	    html = catItemFun({
	    	title: Conf.title,
	    	cover: Conf.cover,
	    	list: voaData.config.list,
	    	song: voaData.song
	    });
	    $(".content-cat").html(html);
	}

	function buildPlayinglist(cat){
		if(cat == playingCat) return;
		playingCat = cat;
		var list = VoaStorage.getStorage().song[cat];
		var html = plTplFun({
			list: list,
			cat: cat
		});
		$('.play-content-playlist').html(html);
	}

	function getCurPos(isFirst){
		window.songMedia = songMedia;
		
		if(songMedia){
			songMedia.getCurrentPosition(
		        // success callback
		        function (position) {
		            if (position > -1) {
		            	if(isFirst){
		            		var dur = songMedia.getDuration(),
					    		m = Math.floor(dur/60),
					    		s = Math.ceil(dur%60);
					    	$('.play-duration').html((m<10 ? '0'+m : m) +':'+ (s<10?'0'+s: s));
		            	}
		                var dur = songMedia.getDuration();
		                var per = position/dur*100;
		                var m = Math.floor(position/60),
	        				s = Math.ceil(position%60),
	        				timeDesc = (m<10 ? '0'+m : m) +':'+ (s<10?'0'+s: s);
	        			$('.mi-time').html(timeDesc);
	        			$('.play-cur-time').html(timeDesc);

		                $('.play-progress-dot').css('left', per+'%');
		                Lyric.move(position);
		                setTimeout(getCurPos, 1000);
		            }
		        },
		        // error callback
		        function (e) {
		            console.log("Error getting pos=" + e);
		        }
		    );
			
		}
	}

	function seekTo(per){
		if(!songMedia) return;
		var dur = songMedia.getDuration();
		songMedia.seekTo(per*dur*1000);
	}

	function playSong(songData){
		var cat = songData.cat;
		curSong = songData;
		if(songMedia){
			songMedia.stop();
			songMedia.release();
		}
		songMedia = new Media(
			cordova.file.externalRootDirectory+'51voa/mp3/'+cat+'/'+songData.name+'.mp3',
	        // success callback
	        function () {
	        	songMedia = null;
	        	playNext();
	        },
	        // error callback
	        function (err) {
	        	songMedia = null;
	        }
	    );
	    songMedia.play();
    	getCurPos(true);

    	rootDirEntry.getFile('article/'+cat+'/'+songData.name+'.txt', {}, function(fileEntry) {
			// Get a File object representing the file,
		    // then use FileReader to read its contents.
		    fileEntry.file(function(file) {
				var reader = new FileReader();
				reader.onloadend = function(e) {
					var text = this.result;
					text = text.replace(/\n/g,'<br><br>');
					
					$('.play-content-text').html(text);
				};

				reader.readAsText(file);
		    }, function(e){
		    	console.err('trans error 2:', e);
		    });

		}, function(e){
	    	console.log('trans error 1', e);
	    });

    	if(songData.hasLyric){
    		Lyric.play(
		    	'lyric/'+cat+'/'+songData.name+'.lrc'
		    );
    	}else{
    		$('.play-content-lyric').html('<div class="play-no-lyric">没有歌词</div>')
    	}
    	if(songData.hasTranslation){
    		rootDirEntry.getFile('translation/'+cat+'/'+songData.name+'.txt', {}, function(fileEntry) {

			    // Get a File object representing the file,
			    // then use FileReader to read its contents.
			    fileEntry.file(function(file) {
					var reader = new FileReader();

					reader.onloadend = function(e) {
						var text = this.result;
						text = text.replace(/\n/g,'<br><br>');
						$('.play-content-translation').html(text);
					};

					reader.readAsText(file);
			    }, function(e){
			    	console.log('trans error 2', e);
			    });

			}, function(e){
		    	console.log('trans error 1', e);
		    });	
    	}else{
    		$('.play-content-translation').html('没有翻译');
    	}
    	
	    $('.play-btn-play').removeClass('play-btn-paused');

	    //更换封面
	    var coverUrl;
	    if(songData.hasImg)
	    	coverUrl = cordova.file.externalRootDirectory + '51voa/image/'+songData.cat+'/'+songData.name+'.jpg';
	    else
	    	coverUrl = 'img/cat-cover/'+Conf.cover[songData.cat];
	    
	    $('.mi-song-cover').css('background-image', 'url("'+coverUrl+'")');
	    $('.play-content-cover-img').css('background-image', 'url("'+coverUrl+'")');
	    $('.page-play-bg').css('background-image', 'url("'+coverUrl+'")');
	    //设置音乐信息
	    $('.mi-title').html(songData.name);
	    $('.mi-cat').html(songData.cat);
	    $('.play-song-title').html(songData.name);
	    $('.play-song-cat').html(songData.cat);

	    $('.doc').addClass('play-zone');
	}
	function playNext(){
		if(playingMode=="single")
			playSong(curSong);
		else{
			var voaData = VoaStorage.getStorage();
			var songList = voaData.song[curSong.cat];
			if(songList.length<1) return;
			if(playingMode == 'random'){
				var index = Math.round(Math.random()*(songList.length-1));
				playSong(songList[index]);
			}else{
				var index = songList.indexOf(curSong) || 0;
				index++;
				if(index < songList.length){
					playSong(songList[index]);
				}else{
					if(playingMode=='loop'){
						playSong(songList[0]);
					}
				}
			}
		}
	}

	function swipeContent(index){
		if(index<0)
			index=0;
		if(index>4)
			index = 4;
		if(index == curContentIndex) return;

		var oldType = contentType[curContentIndex];
        curContentIndex = index;
        var type = contentType[curContentIndex];
        $('.play-content-box').removeClass('play-content-cur-'+oldType).addClass('play-content-cur-'+type);
        $('.play-mini-nav-item')
            .removeClass('play-mini-nav-item-cur')
            .eq(curContentIndex)
            .addClass('play-mini-nav-item-cur');
	}
	function initDotMove(){
		var dot = $('.play-progress-dot'),
			docWidth = $(window).width() || 1,
	    	da,
	    	x;
	    function changePos(){
	    	var per = x/docWidth;
	    	dot.css('left', x+'px');
	    	seekTo(per<0 ? 0 :(per>1 ? 1:per));
	    }
	    function dotMove(e){
	    	e.preventDefault();
	    	x = e.changedTouches[0].clientX;
	    	var t = new Date();
	    	if(t-da > 100){
	    		da = t;
	    		changePos();
		    }
	    }
	    function offDotMove(e){
	    	changePos();
	    	$(document.body)
	    		.off('touchmove', dotMove)
	    		.off('touchleave', offDotMove)
	    		.off('touchcancel', offDotMove)
	    		.off('touchend', offDotMove);
	    }
	    dot.on('touchstart', function(e){
	    	da = new Date();
	    	x = e.changedTouches[0].clientX;
	    	$(document.body)
	    		.on('touchmove', dotMove)
	    		.on('touchleave', offDotMove)
	    		.on('touchend', offDotMove)
	    		.on('touchcancel', offDotMove);
	    });
	}
	function init(){
		catItemFun = $("#catTpl").html().tmpl();
		songListFun = $('#songListTpl').html().tmpl();
		plTplFun = $('#playinglistTpl').html().tmpl();
		update();
		var storePlayingCat = VoaStorage.get('playingCat');
		if(storePlayingCat)
			buildPlayinglist(storePlayingCat);
		playingMode = VoaStorage.get('playingMode') || 'loop';
		$('.play-btn-mode').addClass('play-btn-mode-'+playingMode);

		$('.content-cat').delegate('.cat-item', 'tap', function(){
			var catItem = $(this),
				cat = catItem.data('cat');
			$('.page-song-list .btn-return').html(Conf.title[cat]);
			var voaData = VoaStorage.getStorage();
			var html = songListFun({
				list: voaData.song[cat],
				cat: cat
			});
			$('.page-song-list .ui-content').html(html);
			$('.doc').addClass('song-list-zone');
		});
		$('.page-song-list .btn-return').tap(function(){
	    	$('.doc').removeClass('song-list-zone');
	    });

		$('.page-song-list .ui-content').delegate('.song-list-item', 'tap', function(){
			var item = $(this),
				cat = item.data('cat');

			var songData = VoaStorage.getSongByUid(item.data('uid'), cat);
			if(!songData) return;
			playSong(songData);
			buildPlayinglist(cat);
			swipeContent(1);
		});


		//event for minibar
		$('.mi-song-cover, .mi-song-info, .mi-list-btn').tap(function(){
			$('.doc').addClass('play-zone');
		});

		//event for play control
		$('.play-btn-play, .mi-play-btn').tap(function(){
			var btn = $('.play-btn-play'),
				miBtn = $('.mi-play-btn');
			if(btn.hasClass('play-btn-paused')){
				btn.removeClass('play-btn-paused');
				miBtn.removeClass('mi-paused-btn');
				if(songMedia){
					songMedia.play();
				}
			}else{
				btn.addClass('play-btn-paused');
				miBtn.addClass('mi-paused-btn');
				if(songMedia){
					songMedia.pause();
				}
			}
		});

		$('.mi-list-btn').tap(function(){
			swipeContent(0);
		})
	    $('.play-content-box').swipeRight(function(){
	        if(curContentIndex==0) return;
	        swipeContent(curContentIndex-1);    
	    });
	    $('.play-content-box').swipeLeft(function(){
	        if(curContentIndex==4) return;
	        swipeContent(curContentIndex+1);    
	    });
	    $('.play-collapse').tap(function(){
	        $('.doc').removeClass('play-zone');
	    });

	    $('.play-btn-mode').tap(function(){
	    	var index = modeList.indexOf(playingMode);
	    	index = (index+1)%modeList.length;
	    	$(this)
	    		.removeClass('play-btn-mode-'+playingMode)
	    		.addClass('play-btn-mode-'+modeList[index]);
	    	playingMode = modeList[index];
	    });

	    initDotMove();
	}
	return{
		init: init,
		update: update,
		buildPlayinglist: buildPlayinglist
	}
})();